package com.tencent.cloud.iov.util;

import android.support.annotation.NonNull;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

/**
 * 日期、时间工具类
 *
 * @author showxiao
 * @date 2018/9/14
 */
public class DateTimeUtils {

    private static final String DEFAULT_DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";

    private static volatile ThreadLocal<SimpleDateFormat> sDateFormatThreadLocal;

    public static String getCurDateTime() {
        return getCurDateTime(DEFAULT_DATE_TIME_FORMAT);
    }

    public static String getCurDateTime(String format) {
        SimpleDateFormat dateFormat = getDateFormat();
        dateFormat.applyPattern(format);
        return dateFormat.format(Calendar.getInstance().getTime());
    }

    public static String getDateTime(long millisTime) {
        return getDateTime(millisTime, DEFAULT_DATE_TIME_FORMAT);
    }

    public static String getDateTime(long millisTime, String format) {
        SimpleDateFormat dateFormat = getDateFormat();
        dateFormat.applyPattern(format);
        return dateFormat.format(new Date(millisTime));
    }

    @NonNull
    private static SimpleDateFormat getDateFormat() {
        if (sDateFormatThreadLocal == null) {
            synchronized (DateTimeUtils.class) {
                if (sDateFormatThreadLocal == null) {
                    sDateFormatThreadLocal = new ThreadLocal<SimpleDateFormat>() {
                        @Override
                        protected SimpleDateFormat initialValue() {
                            return new SimpleDateFormat(DEFAULT_DATE_TIME_FORMAT, Locale.getDefault());
                        }
                    };
                }
            }
        }

        return sDateFormatThreadLocal.get();
    }

}
